<template>
	<view>
		<view class="boxContrainer">
			<view class="titlBox"><text class="title">费用信息</text></view>
			<view style="padding-bottom: 20rpx">
				<uni-table ref="table" border stripe>
					<uni-tr>
						<uni-th width="100" align="center"
							><text style="color: #2879ff">收费项目</text>
						</uni-th>
						<uni-th width="100" align="center"
							><text style="color: #2879ff">收款状态</text>
						</uni-th>
						<uni-th width="100" align="center"
							><text style="color: #2879ff">应收金额</text>
						</uni-th>
						<uni-th width="100" align="center"
							><text style="color: #2879ff">已收金额</text>
						</uni-th>
						<uni-th width="100" align="center"
							><text style="color: #2879ff">待收金额</text>
						</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in payFeeList" :key="index">
						<uni-td align="center">{{ item.remark }}</uni-td>
						<uni-td align="center">{{ item.payStatus == 1 ? "待收款" : "已收款" }}</uni-td>
						<uni-td align="center">{{ item.cost }}</uni-td>
						<uni-td align="center">{{ item.paidAmount }}</uni-td>
						<uni-td align="center">{{ item.unpaidAmount }}</uni-td>
					</uni-tr>
				</uni-table>
			</view>
		</view>

		<view class="formInfo">
			<u--form
				class="item"
				label-width="100"
				labelPosition="left"
				:model="form"
				:rules="rules"
				ref="uForm">
				<u-form-item label="车辆油量:" prop="fuelCapacity" required ref="fuelCapacity">
					<view v-if="order.control == '0'">
						<view style="width: 85%; display: inline-block">
							<u-slider
								style="width: 340rpx"
								v-model="form.fuelCapacity"
								min="0"
								:max="16"></u-slider>
						</view>
						<view style="width: 10%; display: inline-block">
							<text>{{ form.fuelCapacity }}/16</text>
						</view>
					</view>
					<view style="width: 100%" v-if="order.control == '1'">
						<view>
							<text v-if="form.fuelType == '1'">{{ form.fuelCapacity }} %</text>
							<text v-if="form.fuelType == '0'">{{ form.fuelCapacity }} 升</text>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="车辆公里数:" prop="vehicleMileage" required ref="vehicleMileage">
					<u--input
						v-model="form.vehicleMileage"
						type="number"
						placeholder="请填写车辆公里数"></u--input>
				</u-form-item>
				<u-form-item label="验车时间:" prop="takeAlsoTime" required ref="takeAlsoTime">
					<uni-datetime-picker type="datetime" v-model="form.takeAlsoTime" />
				</u-form-item>
				<u-form-item label="随车物品:" prop="accessoryItems" ref="accessoryItems">
					<uni-data-checkbox
						mode="tag"
						multiple
						v-model="accessoryItems"
						:localdata="carAccessoriesList"
						@change="checkAccessories"></uni-data-checkbox>
				</u-form-item>

				<template v-if="escrowInfo && escrowInfo.carSource == 6">
					<u-form-item label="托管单价:" prop="escrowUnitPrice" required ref="escrowUnitPrice">
						<div class="flex-row-center">
							<u--input
								v-model="form.escrowUnitPrice"
								@input="check1"
								type="digit"
								placeholder="请输入单价"></u--input>
							<text>元/天</text>
						</div>
					</u-form-item>
					<u-form-item label="用车天数:" prop="escrowOrderDays" required ref="escrowOrderDays">
						<div class="flex-row-center">
							<u--input
								v-model="form.escrowOrderDays"
								@input="check2"
								type="digit"
								placeholder="请输入用车天数"></u--input>
							<text>天</text>
						</div>
					</u-form-item>
					<u-form-item label="托管费用:" prop="escrowAmount" required ref="escrowAmount">
						<div class="flex-row-center">
							<u--input
								v-model="form.escrowAmount"
								@input="check3"
								type="digit"
								placeholder="请输入托管费用"></u--input>
							<text>元</text>
						</div>
					</u-form-item>
				</template>

				<u-form-item label="其他描述:" prop="remark" ref="remark">
					<u--textarea
						v-model="form.remark"
						count
						maxlength="200"
						placeholder="请输入说明"></u--textarea>
				</u-form-item>

				<!-- 自定义费用项目列表 -->
				<view v-if="customCostList.length > 0">
					<view
						class="costItem flex-row-center-sb"
						v-for="(item, index) in customCostList"
						:key="index">
						<text style="color: #333333; font-size: 28rpx">{{ item.deductionsFor }}</text>
						<view class="flex-row-center">
							<text style="color: #333333; font-size: 28rpx"
								>¥{{ item.deductionsAmount || 0 }}</text
							>
							<view style="margin: 0 26rpx" @click="addCustomCost(2, index, item)">
								<u-icon name="edit-pen" color="#2879FF" size="24"></u-icon>
							</view>
							<view @click="deleteCostItem(index)"
								><u-icon name="trash" color="#2879FF" size="24"></u-icon
							></view>
						</view>
					</view>
				</view>

				<view class="flex-xy-center" @click="addCustomCost(1)">
					<view class="flex-row-center addCost">
						<u-icon name="plus-circle" color="#fff"></u-icon>
						<text style="color: #fff; font-size: 26rpx; margin-left: 20rpx">添加收费项</text>
					</view>
				</view>

				<view class="text-line"><text class="text-name">车身照片</text></view>
				<view class="text-line"
					><sr-upload maxCount="10" @uploadResult="bodyImageChange"></sr-upload
				></view>

				<view class="text-line"><text class="text-name">仪表盘/油表照片</text></view>
				<view class="text-line"
					><sr-upload maxCount="10" @uploadResult="panelImageChange"></sr-upload
				></view>

				<view class="text-line"><text class="text-name">车辆内饰照片</text></view>
				<view class="text-line"
					><sr-upload maxCount="10" @uploadResult="interiorImageChange"></sr-upload
				></view>

				<view class="text-line"><text class="text-name">车辆划痕照片</text></view>
				<view class="text-line"
					><sr-upload maxCount="10" @uploadResult="scratchImageChange"></sr-upload
				></view>

				<view class="text-line"><text class="text-name">还车验车视频</text></view>
				<view class="text-line"
					><sr-upload maxCount="1" accept="video" @uploadResult="uploadVideo"></sr-upload>
				</view>

				<view class="signImage-box">
					<u-form-item label="客户签名:" prop="signImage" ref="signImage">
						<image
							:src="signImage"
							@click="test"
							style="height: 90px; width: 100%; border: 0.5px #dadbde solid"></image>
					</u-form-item>
				</view>
			</u--form>
		</view>
		<!-- </view> -->
		<!--		<button type="info" :loading="loading" class="sub-btn" @click="distribution">保&nbsp;&nbsp;存</button>-->
		<view class="bottomView flex-row-center-sb">
			<view
				class="btn"
				style="border: 1rpx solid #1673ff; color: #1673ff; background-color: #fff"
				@click="saveSubmit(2)"
				>保存并收款</view
			>
			<view class="btn" @click="saveSubmit(1)">保存</view>
		</view>

		<u-popup :show="showEditCost" mode="bottom" @close="showEditCost = false" closeable round="20">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx 20rpx">
				<view style="margin-bottom: 30rpx">{{ popTitleType == 1 ? "新增" : "编辑" }}费用项</view>
				<uni-forms ref="form">
					<uni-forms-item label="收费项名称" labelWidth="90" required>
						<view
							><u--input
								v-model="customCost.deductionsFor"
								placeholder="请输入收费项名称"></u--input
						></view>
					</uni-forms-item>

					<uni-forms-item label="费用" labelWidth="90" required>
						<view>
							<u--input
								v-model="customCost.deductionsAmount"
								@input="check"
								type="digit"
								placeholder="请输入费用"></u--input>
						</view>
					</uni-forms-item>
				</uni-forms>

				<view class="commitBtn" @click="commitCost">提交</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import srUpload from "@/components/upload/sr-upload.vue";
	import orderInfo from "./component/orderInfo.vue";
	import settings from "@/settings.js";
	import * as api from "@/api/order-api.js";
	export default {
		components: {
			srUpload,
			orderInfo,
			// sign
		},
		data() {
			return {
				loading: false,
				show: false,
				showEditCost: false,
				popTitleType: 1,
				currentEditCostIndex: -1,
				order: {},
				takeAlsoTime: Number(new Date()),
				accessoryItems: [],
				alsoCarItems: [],
				signImage: "",
				form: {
					orderNo: "", //订单编号   必传
					type: 2, //类型(1交车验车,2还车验车)   必传
					fuelCapacity: 0, //车辆油量
					fuelType: 0,
					vehicleMileage: undefined, //公里数
					accessoryItems: "", //车辆随车物品(逗号隔开)
					remark: "", //其他描述
					takeAlsoTime: this.parseTime(new Date()), //取还车时间
					lkosten: "", //补充油费(还车验车)
					bodyImage: [], //车身照片
					panelImage: [], //仪表盘
					interiorImage: [], //内饰照片
					scratchImage: [], //车辆划痕
					signImage: [], //客户签名
					videoUrls: [], //验车视频
					escrowUnitPrice: "", //托管单价
					escrowOrderDays: "", //用车天数
					escrowAmount: "", //托管费用
				},
				carAccessoriesList: [],
				rules: {
					vehicleMileage: {
						type: "number",
						required: true,
						message: "请填写车辆公里数",
						trigger: ["blur", "change"],
					},
					takeAlsoTime: {
						type: "string",
						min: 2,
						required: true,
						message: "请选择验车时间",
						trigger: ["blur", "change"],
					},
					escrowUnitPrice: {
						type: "number",
						required: true,
						message: "请填写托管单价",
						trigger: ["blur", "change"],
					},
					escrowOrderDays: {
						type: "number",
						required: true,
						message: "请填写用车天数",
						trigger: ["blur", "change"],
					},
					escrowAmount: {
						type: "number",
						required: true,
						message: "请填写托管费用",
						trigger: ["blur", "change"],
					},
					// signImage: {
					// 	type: 'array',
					// 	min: 1,
					// 	required: true,
					// 	message: '客户签名不能为空',
					// 	trigger: ['change']
					// }
				},
				customCostList: [],
				customCost: {
					chargeItemsType: 1,
					deductionsFor: "",
					deductionsAmount: "",
					deductionsWay: "2",
				},
				escrowInfo: {},
				payFeeList: [],
				payFeeTypes: [],
				isVehicleKey: false,
			};
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules);
		},
		watch: {
			"form.escrowUnitPrice": {
				handler(value) {
					if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
						this.form.escrowAmount =
							Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays);
					}
				},
				// immediate:true,
				deep: true,
			},
			"form.escrowOrderDays": {
				handler(value) {
					if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
						this.form.escrowAmount =
							Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays);
					}
				},
				// immediate:true,
				deep: true,
			},
		},
		methods: {
			carOil() {
				api.car_oil(this.order.carId).then((res) => {
					if (res.data) {
						this.isVehicleKey = true;
						this.form.fuelCapacity = res.data.fuelLevel;
						this.form.fuelType = res.data.fuelType;
						this.form.vehicleMileage = res.data.mileage;
					} else {
						this.isVehicleKey = false;
					}
				});
			},
			getPayFeeList() {
				api.getAllPaymentOfFees(this.form.orderNo).then((res) => {
					this.payFeeList = res.data || [];
					let payFeeObjs = this.payFeeList.filter((item) => item.payStatus == 1);
					if (payFeeObjs && payFeeObjs.length > 0) {
						this.payFeeTypes = payFeeObjs.map((item) => {
							return item.type;
						});
					}
				});
			},
			getEscrowByOrderNo() {
				api.getEscrowByOrderNo(this.form.orderNo).then((res) => {
					this.escrowInfo = res.data;
					this.form.escrowUnitPrice = this.escrowInfo.escrowUnitPrice;
					this.form.escrowOrderDays = this.escrowInfo.escrowOrderDays;
					this.form.escrowAmount = this.escrowInfo.escrowAmount;
				});
			},
			// 添加或者编辑自定义费用项
			addCustomCost(type, index, info) {
				this.popTitleType = type;
				if (type == 1) {
					//新增
					this.customCost = {};
				} else {
					//编辑
					this.customCost = info;
					this.currentEditCostIndex = index;
				}
				this.showEditCost = true;
			},
			deleteCostItem(index) {
				this.customCostList.splice(index, 1);
			},
			//确定提交费用项
			commitCost() {
				if (this.$u.test.isEmpty(this.customCost.deductionsFor)) {
					uni.$u.toast("费用名称不能为空");
					return;
				} else if (this.$u.test.isEmpty(this.customCost.deductionsAmount)) {
					uni.$u.toast("费用不能为空");
					return;
				} else {
					if (this.popTitleType == 1) {
						//新增
						this.customCostList.push(this.customCost);
					} else {
						//编辑
						this.customCostList[this.currentEditCostIndex].deductionsFor =
							this.customCost.deductionsFor;
						this.customCostList[this.currentEditCostIndex].deductionsAmount =
							this.customCost.deductionsAmount;
					}
					this.showEditCost = false;
				}
			},
			check(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.customCost.deductionsAmount = e;
				});
			},
			check1(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.form.escrowUnitPrice = e;
				});
			},
			check2(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,1})/g)[0] || null;
				this.$nextTick(() => {
					this.form.escrowOrderDays = e;
				});
			},
			check3(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.form.escrowAmount = e;
				});
			},
			test() {
				uni.navigateTo({
					url: "/order/shortOrder/component/sign",
				});
			},
			carAccessories() {
				api.car_accessories().then((res) => {
					res.data.map((item) => {
						this.carAccessoriesList.push({
							value: item.dictValue,
							text: item.dictLabel,
						});
					});
				});
			},
			saveSubmit(type) {
				this.$refs.uForm
					.validate()
					.then((res) => {
						this.loading = true;
						// uni.showLoading({
						// 	title: '提交中...',
						// 	mask: true
						// });
						let param = {
							...this.form,
							takeAlsoTime: this.parseTime(this.form.takeAlsoTime),
							cost: this.customCostList,
							saveType: type,
						};
						api
							.delivery(param)
							.then((data) => {
								if (type == 2) {
									this.goPayFee();
								} else {
									uni.$emit("refreshOrder");
									uni.$u.toast("还车成功");
									uni.navigateBack({
										animationDuration: 300,
									});
								}
							})
							.finally(() => {
								// uni.hideLoading();
								this.loading = false;
							});
					})
					.catch((errors) => {
						uni.$u.toast("必填项不能为空");
					});
			},
			//保存并收款
			goPayFee() {
				api.getAllPaymentOfFees(this.form.orderNo).then((res) => {
					this.payFeeList = res.data || [];
					let payFeeObjs = this.payFeeList.filter((item) => item.payStatus == 1);
					if (payFeeObjs && payFeeObjs.length > 0) {
						this.payFeeTypes = payFeeObjs.map((item) => {
							return item.type;
						});
					}
					if (this.payFeeTypes && this.payFeeTypes.length > 0) {
						let type = this.payFeeTypes.join(",");
						uni.redirectTo({
							url:
								"/order/shortOrder/checkCarOrderPayFee?type=" +
								type +
								"&orderNo=" +
								this.form.orderNo,
						});
					} else {
						uni.$emit("refreshOrder");
						this.$u.toast("还车成功,暂无可缴纳的费用");
						uni.navigateBack({
							animationDuration: 300,
						});
					}
				});
			},
			checkAccessories() {
				if (this.accessoryItems && this.accessoryItems.length > 0) {
					let arr = [];
					this.carAccessoriesList.forEach((item) => {
						if (this.accessoryItems.indexOf(item.value) > -1) {
							arr.push(item.text);
						}
					});
					this.form.accessoryItems = arr.join(",");
				} else {
					this.accessoryItems = "";
				}
			},
			getalsoCarItems() {
				api.alsoCarItems().then((response) => {
					const data = response.data;
					this.customCostList = data.map((val) => {
						return {
							...val,
							checked: false,
							chargeItemsType: 1,
							deductionsFor: val.chargeItemsName,
							deductionsAmount: "",
							deductionsWay: "2",
						};
					});
				});
			},
			bodyImageChange(data) {
				this.form.bodyImage = data;
			},
			panelImageChange(data) {
				this.form.panelImage = data;
			},
			interiorImageChange(data) {
				this.form.interiorImage = data;
			},
			scratchImageChange(data) {
				this.form.scratchImage = data;
			},
			uploadVideo(data) {
				this.form.videoUrls = data;
			},
			// 日期格式化
			parseTime(time, pattern) {
				if (arguments.length === 0 || !time) {
					return null;
				}
				const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
				let date;
				if (typeof time === "object") {
					date = time;
				} else {
					if (typeof time === "string" && /^[0-9]+$/.test(time)) {
						time = parseInt(time);
					} else if (typeof time === "string") {
						time = time
							.replace(new RegExp(/-/gm), "/")
							.replace("T", " ")
							.replace(new RegExp(/\.[\d]{3}/gm), "");
					}
					if (typeof time === "number" && time.toString().length === 10) {
						time = time * 1000;
					}
					date = new Date(time);
				}
				const formatObj = {
					y: date.getFullYear(),
					m: date.getMonth() + 1,
					d: date.getDate(),
					h: date.getHours(),
					i: date.getMinutes(),
					s: date.getSeconds(),
					a: date.getDay(),
				};
				const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
					let value = formatObj[key];
					// Note: getDay() returns 0 on Sunday
					if (key === "a") {
						return ["日", "一", "二", "三", "四", "五", "六"][value];
					}
					if (result.length > 0 && value < 10) {
						value = "0" + value;
					}
					return value || 0;
				});
				return time_str;
			},
		},
		onLoad: function (option) {
			const item = JSON.parse(decodeURIComponent(option.item));
			this.order = item;
			this.form.orderNo = this.order.orderNo;
			this.carAccessories();
			this.getalsoCarItems();
			this.getEscrowByOrderNo();
			this.getPayFeeList();
			this.carOil();
			uni.$on("singImg", (data) => {
				let arr = [];
				arr.push(data.saveUrl);
				this.form.signImage = arr;
				this.signImage = settings.baseImageUrl + data.saveUrl;
			});
		},
	};
</script>

<style lang="scss" scoped>
	.bottomView {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		padding: 0 44rpx;
		background-color: #ffffff;

		.btn {
			height: 88rpx;
			width: 312rpx;
			line-height: 88rpx;
			text-align: center;
			border-radius: 44rpx;
			background-color: #1673ff;
			font-size: 32rpx;
			color: #fff;
		}
	}

	.formInfo {
		margin: 20rpx;
		padding: 20rpx 30rpx;
		background: #ffffff;
		border-radius: 18rpx;
		padding-bottom: 120rpx;
	}

	.text-name {
		width: 155rpx;
		color: #303133;
		font-size: 15px;
	}

	.text-line {
		margin: 0 20rpx 20rpx 20rpx;
	}

	.item {
		margin-bottom: 120rpx;
	}

	.checkbox-box {
		padding: 20rpx;
	}

	.checkbox-item {
		min-width: 165rpx;
		transform: scale(0.9);
	}

	/deep/ .signImage-box .u-form-item .u-form-item__body {
		max-height: 200rpx;
		overflow-y: hidden;
	}

	/deep/ .signImage-box .u-form-item .u-form-item__body .u-form-item__body__right {
		border-width: 0.5px !important;
		border-color: #dadbde !important;
		border-style: solid;
	}

	.addCost {
		margin: 32rpx 0;
		box-sizing: border-box;
		padding-left: 30rpx;
		width: 242rpx;
		height: 60rpx;
		background: #1673ff;
		border-radius: 30rpx;
	}

	.commitBtn {
		background-color: #1673ff;
		border-radius: 12rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		width: 300rpx;
		margin-top: 30rpx;
	}

	.costItem {
		box-shadow: 0px 4rpx 16rpx 0rpx rgba(1, 10, 18, 0.1);
		border-radius: 16rpx;
		margin: 12rpx 0;
		padding: 20rpx;
		background-color: #ffffff;
	}
</style>
